package cpu

import (
	monproto "gollect/proto"
	"time"

	"github.com/shirou/gopsutil/v3/cpu"
)

func init() {
	// The first call to cpu.Percent with a 0 interval will return 0,
	// so we call it here to initialize the measurement.
	// Subsequent calls will return the usage since the last call.
	_, _ = cpu.Percent(0, false)
	_, _ = cpu.Percent(0, true)
}

func Collect(interval time.Duration) *monproto.CpuInfo {
	// Use a very short interval to get immediate CPU stats
	percent, err := cpu.Percent(0, false)
	var totalLoad float64
	if err == nil && len(percent) > 0 {
		totalLoad = percent[0] / 100.0
	}

	percentPerCore, err := cpu.Percent(0, true)
	coreLoads := make([]float32, 0, len(percentPerCore))
	if err == nil {
		for _, p := range percentPerCore {
			coreLoads = append(coreLoads, float32(p/100.0))
		}
	}

	return &monproto.CpuInfo{
		TotalLoad: float32(totalLoad),
		CoreLoads: coreLoads,
	}
} 